package org.tong.filter;

import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;


public class VerificationCodeFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (!("/login/page".equals(httpServletRequest.getRequestURI()) && httpServletRequest.getMethod().equalsIgnoreCase("POST"))) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            String captcha = httpServletRequest.getParameter("captcha");
            String sCaptcha = (String) httpServletRequest.getSession().getAttribute("captcha");
            if (!StringUtils.hasText(captcha)) {
                sendErrorToPage(httpServletResponse, "请输入校验码");
            } else if (!captcha.equals(sCaptcha)) {
                sendErrorToPage(httpServletResponse, "校验码错误");
            } else {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
        }
    }

    private void sendErrorToPage(HttpServletResponse httpServletResponse, String msg) {
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try (OutputStream os = httpServletResponse.getOutputStream();) {
            os.write(msg.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class CaptchaException extends AuthenticationException {

        public CaptchaException(String msg) {
            super(msg);
        }
    }
}
